"""Header_Information
------------------------------------
    File_Name: transaction
    Author: yangzhide
    Date: 2024/10/10
    Description: 中间件文件——作用于全局
------------------------------------
"""
import time
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import Request
import loguru

logger = loguru.logger
log = logger.bind(module="app")


class LoggingMiddleware(BaseHTTPMiddleware):
    """日志记录
    请求方法、url、执行用时
    """
    async def dispatch(self, request: Request, call_next):
        log.info(
            f"IP: {request.client.host} "
            f"Request: {request.method} {request.url}"
        )
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        log.info(
            f"IP: {request.client.host} "
            f"Request: {request.method} {request.url} -> "
            f"Status: {response.status_code} "
            f"Time: {process_time:.2f}s"
        )
        return response
